home *** CD-ROM | disk | FTP | other *** search
/ Total Network Tools 2002 / NextStepPublishing-TotalNetworkTools2002-Win95.iso / Archive / Misc Servers / Zope.exe / M_SYSLOG.PY < prev    next >
Encoding:
Text File  |  2000-06-02  |  8.5 KB  |  236 lines

  1. # -*- Mode: Python; tab-width: 4 -*-
  2.  
  3. # ======================================================================
  4. # Copyright 1997 by Sam Rushing
  5. #                         All Rights Reserved
  6. # Permission to use, copy, modify, and distribute this software and
  7. # its documentation for any purpose and without fee is hereby
  8. # granted, provided that the above copyright notice appear in all
  9. # copies and that both that copyright notice and this permission
  10. # notice appear in supporting documentation, and that the name of Sam
  11. # Rushing not be used in advertising or publicity pertaining to
  12. # distribution of the software without specific, written prior
  13. # permission.
  14. # SAM RUSHING DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
  15. # INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN
  16. # NO EVENT SHALL SAM RUSHING BE LIABLE FOR ANY SPECIAL, INDIRECT OR
  17. # CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  18. # OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT,
  19. # NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  20. # CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  21. # ======================================================================
  22.  
  23. """socket interface to unix syslog.
  24. On Unix, there are usually two ways of getting to syslog: via a
  25. local unix-domain socket, or via the TCP service.
  26.  
  27. Usually "/dev/log" is the unix domain socket.  This may be different
  28. for other systems.
  29.  
  30. >>> my_client = syslog_client ('/dev/log')
  31.  
  32. Otherwise, just use the UDP version, port 514.
  33.  
  34. >>> my_client = syslog_client (('my_log_host', 514))
  35.  
  36. On win32, you will have to use the UDP version.  Note that
  37. you can use this to log to other hosts (and indeed, multiple
  38. hosts).
  39.  
  40. This module is not a drop-in replacement for the python
  41. <syslog> extension module - the interface is different.
  42.  
  43. Usage:
  44.  
  45. >>> c = syslog_client()
  46. >>> c = syslog_client ('/strange/non_standard_log_location')
  47. >>> c = syslog_client (('other_host.com', 514))
  48. >>> c.log ('testing', facility='local0', priority='debug')
  49.  
  50. """
  51.  
  52. # TODO: support named-pipe syslog.
  53. # [see ftp://sunsite.unc.edu/pub/Linux/system/Daemons/syslog-fifo.tar.z]
  54.  
  55. # from <linux/sys/syslog.h>:
  56. # ===========================================================================
  57. # priorities/facilities are encoded into a single 32-bit quantity, where the
  58. # bottom 3 bits are the priority (0-7) and the top 28 bits are the facility
  59. # (0-big number).  Both the priorities and the facilities map roughly
  60. # one-to-one to strings in the syslogd(8) source code.  This mapping is
  61. # included in this file.
  62. #
  63. # priorities (these are ordered)
  64.  
  65. LOG_EMERG       = 0     #  system is unusable 
  66. LOG_ALERT       = 1     #  action must be taken immediately 
  67. LOG_CRIT        = 2     #  critical conditions 
  68. LOG_ERR         = 3     #  error conditions 
  69. LOG_WARNING     = 4     #  warning conditions 
  70. LOG_NOTICE      = 5     #  normal but significant condition 
  71. LOG_INFO        = 6     #  informational 
  72. LOG_DEBUG       = 7     #  debug-level messages 
  73.  
  74. #  facility codes 
  75. LOG_KERN        = 0     #  kernel messages 
  76. LOG_USER        = 1     #  random user-level messages 
  77. LOG_MAIL        = 2     #  mail system 
  78. LOG_DAEMON      = 3     #  system daemons 
  79. LOG_AUTH        = 4     #  security/authorization messages 
  80. LOG_SYSLOG      = 5     #  messages generated internally by syslogd 
  81. LOG_LPR         = 6     #  line printer subsystem 
  82. LOG_NEWS        = 7     #  network news subsystem 
  83. LOG_UUCP        = 8     #  UUCP subsystem 
  84. LOG_CRON        = 9     #  clock daemon 
  85. LOG_AUTHPRIV    = 10    #  security/authorization messages (private) 
  86.  
  87. #  other codes through 15 reserved for system use 
  88. LOG_LOCAL0      = 16        #  reserved for local use 
  89. LOG_LOCAL1      = 17        #  reserved for local use 
  90. LOG_LOCAL2      = 18        #  reserved for local use 
  91. LOG_LOCAL3      = 19        #  reserved for local use 
  92. LOG_LOCAL4      = 20        #  reserved for local use 
  93. LOG_LOCAL5      = 21        #  reserved for local use 
  94. LOG_LOCAL6      = 22        #  reserved for local use 
  95. LOG_LOCAL7      = 23        #  reserved for local use 
  96.  
  97. priority_names = {
  98.     "alert":    LOG_ALERT,
  99.     "crit":     LOG_CRIT,
  100.     "debug":    LOG_DEBUG,
  101.     "emerg":    LOG_EMERG,
  102.     "err":      LOG_ERR,
  103.     "error":    LOG_ERR,        #  DEPRECATED 
  104.     "info":     LOG_INFO,
  105.     "notice":   LOG_NOTICE,
  106.     "panic":    LOG_EMERG,      #  DEPRECATED 
  107.     "warn":     LOG_WARNING,        #  DEPRECATED 
  108.     "warning":  LOG_WARNING,
  109.     }
  110.  
  111. facility_names = {
  112.     "auth":     LOG_AUTH,
  113.     "authpriv": LOG_AUTHPRIV,
  114.     "cron":     LOG_CRON,
  115.     "daemon":   LOG_DAEMON,
  116.     "kern":     LOG_KERN,
  117.     "lpr":      LOG_LPR,
  118.     "mail":     LOG_MAIL,
  119.     "news":     LOG_NEWS,
  120.     "security": LOG_AUTH,       #  DEPRECATED 
  121.     "syslog":   LOG_SYSLOG,
  122.     "user":     LOG_USER,
  123.     "uucp":     LOG_UUCP,
  124.     "local0":   LOG_LOCAL0,
  125.     "local1":   LOG_LOCAL1,
  126.     "local2":   LOG_LOCAL2,
  127.     "local3":   LOG_LOCAL3,
  128.     "local4":   LOG_LOCAL4,
  129.     "local5":   LOG_LOCAL5,
  130.     "local6":   LOG_LOCAL6,
  131.     "local7":   LOG_LOCAL7,
  132.     }
  133.  
  134. import socket
  135.  
  136. class syslog_client:
  137.     def __init__ (self, address='/dev/log'):
  138.         self.address = address
  139.         if type (address) == type(''):
  140.             try: # APUE 13.4.2 specifes /dev/log as datagram socket
  141.                 self.socket = socket.socket( socket.AF_UNIX
  142.                                                        , socket.SOCK_DGRAM)
  143.                 self.socket.connect (address)
  144.             except: # older linux may create as stream socket
  145.                 self.socket = socket.socket( socket.AF_UNIX
  146.                                                        , socket.SOCK_STREAM)
  147.                 self.socket.connect (address)
  148.             self.unix = 1
  149.         else:
  150.             self.socket = socket.socket( socket.AF_INET
  151.                                                    , socket.SOCK_DGRAM)
  152.             self.unix = 0
  153.  
  154.     # curious: when talking to the unix-domain '/dev/log' socket, a
  155.     #   zero-terminator seems to be required.  this string is placed
  156.     #   into a class variable so that it can be overridden if
  157.     #   necessary.
  158.  
  159.     log_format_string = '<%d>%s\000'
  160.  
  161.     def log (self, message, facility=LOG_USER, priority=LOG_INFO):
  162.         message = self.log_format_string % (
  163.             self.encode_priority (facility, priority),
  164.             message
  165.             )
  166.         if self.unix:
  167.             self.socket.send (message)
  168.         else:
  169.             self.socket.sendto (message, self.address)
  170.  
  171.     def encode_priority (self, facility, priority):
  172.         if type(facility) == type(''):
  173.             facility = facility_names[facility]
  174.         if type(priority) == type(''):
  175.             priority = priority_names[priority]         
  176.         return (facility<<3) | priority
  177.  
  178.     def close (self):
  179.         if self.unix:
  180.             self.socket.close()
  181.  
  182. if __name__ == '__main__':
  183.     """
  184.        Unit test for syslog_client.  Set up for the test by:
  185.     
  186.     * tail -f /var/log/allstuf (to see the "normal" log messages).
  187.  
  188.         * Running the test_logger.py script with a junk file name (which
  189.       will be opened as a Unix-domain socket). "Custom" log messages
  190.       will go here.
  191.  
  192.     * Run this script, passing the same junk file name.
  193.  
  194.     * Check that the "bogus" test throws, and that none of the rest do.
  195.  
  196.     * Check that the 'default' and 'UDP' messages show up in the tail.
  197.  
  198.     * Check that the 'non-std' message shows up in the test_logger
  199.       console.
  200.  
  201.     * Finally, kill off the tail and test_logger, and clean up the
  202.       socket file.
  203.     """
  204.     import sys, traceback
  205.  
  206.     if len( sys.argv ) != 2:
  207.        print "Usage: syslog.py localSocketFilename"
  208.        sys.exit()
  209.  
  210.     def test_client( desc, address=None ):
  211.         try:
  212.             if address:
  213.                 client = syslog_client( address )
  214.             else:
  215.                 client = syslog_client()
  216.         except:
  217.             print 'syslog_client() [%s] ctor threw' % desc
  218.             traceback.print_exc()
  219.             return
  220.  
  221.         try:
  222.             client.log( 'testing syslog_client() [%s]' % desc
  223.                       , facility='local0', priority='debug' )
  224.             print 'syslog_client.log() [%s] did not throw' % desc
  225.         except:
  226.             print 'syslog_client.log() [%s] threw' % desc
  227.             traceback.print_exc()
  228.  
  229.     test_client( 'default' )
  230.     test_client( 'bogus file', '/some/bogus/logsocket' )
  231.     test_client( 'nonstd file', sys.argv[1] )
  232.     test_client( 'UDP',  ('localhost', 514) )
  233.